﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Cofe.Core.Logger
{
    public abstract class EventSource<T> : IEventSource<T>
        where T : EventArgs
    {
        #region Constructor

        protected EventSource(CancellationToken token)
        {
            CancellationToken = token;            
        }

        protected EventSource()
        {
            _cts = new CancellationTokenSource();
            CancellationToken = _cts.Token;            
        }

        #endregion

        #region Methods

        protected virtual void OnEnabled() { }
        protected virtual void OnDisabled() { }


        public void Dispose()
        {
            //if (_cts != null)
            //    _cts.Cancel();
        }

        protected void dispatchEvent(T eventToDispatch)
        {
            if (_isEventEnabled && OnEvent != null)
                OnEvent(this, eventToDispatch);
        }

        #endregion

        #region Data

        protected List<Type> _supportedEventType = new List<Type>()
        {
            typeof(T)
        };
        private bool _isEventEnabled = true;
        private CancellationTokenSource _cts = null;

        #endregion

        #region Public Properties

        public IEnumerable<Type> SupportedEventType { get { return _supportedEventType; } }

        public event EventHandler<T> OnEvent;

        public bool IsEventEnabled
        {
            get { return _isEventEnabled; }
            set
            {
                if (_isEventEnabled != value)
                {
                    if (value) OnEnabled();
                    else OnDisabled();
                    _isEventEnabled = value;
                }
            }
        }

        public CancellationToken CancellationToken { get; private set; }

        #endregion






    
    }
}
